var util = require('../../../utils/util.js');
var wxUtil = require('../../../utils/wxUtil.js');
var ajax = require('../../../utils/ajax.js');
var common = require('../../../utils/common.js');
var PageBase = require('../../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
    data: {
        dataLoaded: false,
        couponsVisible: false,
        useCoupon: true, //是否使用代金券
        curCoupon: null, //当前选中的券
        payAmount: 0, //实付金额
        paying: false,
        stopClick: false,
        orderId: '',
        orderInfo: {},
        goodsList: []

    },

    onLoad: function(options) {
        this._options = options;
        common.initApp({
            loginSuc: () => {
                this._fetch();
            }
        });
    },

    _fetch() {
        var {
            orderno
        } = this._options;

        ajax.G({
            url: 'm=store&c=order',
            data: {
                orderno: orderno,
            },
            success: (res) => {
                //debugger;
                var {
                  createtime,
                  money,
                  orderno,
                  orders,
                  remark,
                  shopname
                } = res.data[0];
                var goodsAmount = 0;
                var curCoupon;

                // couponList.forEach((coupon) => {
                //     if (bestCouponId == coupon.id) {
                //         curCoupon = coupon;
                //         coupon.checked = true;
                //     } else {
                //         coupon.checked = false;
                //     }
                // })
                // goodsList.forEach((goods) => {
                //     goodsAmount += parseInt(goods.amount);
                // });
                // orderInfo.goodsAmount = goodsAmount;

                this.setData({
                    dataLoaded: true,
                    createtime,
                    money,
                    orderno,
                    orders,
                    remark,
                    shopname
                });

                this._calMoney();
            }
        });
    },

    /**
     * 显示代金券选择列表
     * @return {[type]} [description]
     */
    _showCouponList() {
        this.setData({
            couponsVisible: true
        });
    },

    /**
     * 选择代金券
     * @param  {[type]} evt [description]
     * @return {[type]}     [description]
     */
    _selectCoupon(evt) {
        var {
            couponList
        } = this.data;
        var curCoupon;

        couponList.forEach((coupon) => {
            if (evt.detail.value == coupon.id) {
                curCoupon = coupon;
                coupon.checked = true;
            } else {
                coupon.checked = false;
            }
        });

        this.setData({
            couponList,
            curCoupon,
        });
        this._calMoney();
    },

    /**
     * 隐藏代金券列表
     * @return {[type]} [description]
     */
    _hideCouponList() {
        this.setData({
            couponsVisible: !this.data.couponsVisible
        });
    },

    /**
     * 禁用或启用代金券列表
     * @param  {[type]} evt [description]
     * @return {[type]}     [description]
     */
    _disabledCoupon(evt) {
        this.setData({
            useCoupon: evt.detail.value,
        });
        this._calMoney();
    },

    /**
     * 计算实付金额
     * @return {[type]} [description]
     */
    _calMoney() {
        var {
            orderInfo,
            curCoupon,
            useCoupon
        } = this.data;
        var orderAmount = parseFloat(orderInfo.order_amount); //订单金额
        var couponAmount = parseFloat(curCoupon ? curCoupon.coupon_amount : 0);
        var payAmount = 0;

        if (useCoupon) {
            payAmount = orderAmount - couponAmount;
        } else {
            payAmount = orderAmount;
        }
        if (payAmount < 0) {
            payAmount = 0;
        }

        this.setData({
            payAmount: parseFloat(payAmount).toFixed(2)
        });
    },

    /**
     * 支付
     * @return {[type]} [description]
     */
    _payOrder() {
       var $this = this;

        var {
            orderno
        } = this.data;

        this.setData({
            paying: true,
            stopClick: true
        })

        setTimeout(() => {
            this.setData({
                stopClick: false
            })
        }, 5000);

        ajax.P({
            url: 'm=store&c=orderpay',
            data: {
                orderno,
                uid: app.getUid()
                //open_id: app.getOpenId()
            },
            success: (res) => {
                //debugger;

                var data = res.data;


                var wxPayParams = {
                  timeStamp: String(data.timestamp),
                  nonceStr: data.nonce_str,
                  package: data.package,
                  paySign: data.sign
                };

                $this._paySuccess(wxPayParams);

                // if (payType == 0) { //使用代金券支付成功
                //     this.setData({
                //         paying: false,
                //         orderId,
                //         payAmount
                //     })
                //     util.alert('代金券抵扣成功', () => {
                //         wx.redirectTo({
                //             url: '/pages/paySuccess/index?orderId=' + orderId + '&totalPrice=' + payAmount
                //         });
                //     })

                // } else if (payType == 1) { //支付宝
                // } else if (payType == 2) { //微信
                //     this._paySuccess(wxPayParams, orderId, payAmount);
                // }
            }

        });
    },

    /**
     * 微信支付成功回调
     */
    _paySuccess(wxPayParams) {
        var _self = this;
        this.setData({
            paying: false
        })
        // if (typeof wxPayParams == 'string') {
        //     wxPayParams = JSON.parse(wxPayParams);
        // }

        wxUtil.wxPay(wxPayParams);

        wxPayParams.success = function() {
            //debugger;
            wx.redirectTo({
              url: '/pages/shop/paySuccess/index?orderno=' + this.data.orderno + '&money=' + this.data.money
            });
        }.bind(this);


        wxPayParams.fail = function () {
          //debugger;
          util.showWarn("支付失败");
        }.bind(this);

    },

}));